
import { invoke } from '@tauri-apps/api/core';
import { DeleteCondition, DeleteOptions, QueryCondition, QueryExtention, QueryOptions, UpdateCondition, UpdateOptions } from '../types';
import optionsWrap from '@/components/datasets/create/website/base/options-wrap';
import { DataSource } from '@/services/data-source';
import { createDirs, homePath, saveText, uuid } from '@/utils';
import { create } from '@tauri-apps/plugin-fs';
import { dsInsert } from '../datasource';
import { PROJECT_APPLICATION_CLASS_IDENTIFIER } from '@/services/constants';
import { ProjectApplication, } from './application';


export interface AgentChatRequestMessage {
    conversation_id: string;
    parent_message_id?: string;
    files: string[];
    inputs: string[];
    query: string;
    response_mode: 'streaming' | 'blocking' | string;
}

export interface AgentChatResponseMessage {
    limit: number,
    has_more: boolean,
    data: AgentChatResponseMessageItem[],
}

export interface AgentChatResponseMessageItem {
    id: string,
    conversation_id: string,
    inputs: string[],
    query: string,
    message: string,
    message_tokens: number,
    answer: string,
    answer_tokens: number,
    provider_response_latency: number,
    workflow_run_id?: string,
    message_files: string[],
    parent_message_id?: string,
}

export const appAgentChatSend = async (identifier: string, isInstalled: boolean, message: AgentChatRequestMessage): Promise<AgentChatResponseMessage | null> => {

    console.log(identifier, isInstalled, message);

    let res: any = await invoke('plugin:mg-platform|app_agent_chat_send', {
        identifier: identifier,
        isInstalled: isInstalled,
        message: message,
    });
    console.log(res);
    return res;
}

export const appCreateEmptyAgent = async (value: ProjectApplication): Promise<any> => {
    const { name, icon, } = value;
    //新建一个空的AGENT 
    let applicationIdentifier = value.identifier ? value.identifier : uuid();
    try {
        //创建文件
        let home = await homePath();
        let exportPath = `${home}/projects/${value.project_identifier}/${applicationIdentifier}/`;
        await createDirs(exportPath);
        let filename = `${exportPath}/agent.json`;
        await create(filename);
        await saveText(filename, JSON.stringify({
            ...AGENT_JSON,
            id: applicationIdentifier,
            name: value.title || value.name,
        }));
        value.path = filename;
    } catch (err) {
        console.error(err);
    }
    return
}

export default {}


const AGENT_JSON = {
    "id": "9e208067-284b-49aa-9594-d5cb443d4fbb",
    "name": "Agent",
    "description": "",
    "mode": "agent-chat",
    "icon_type": "emoji",
    "icon": "🤖",
    "icon_background": "#FFEAD5",
    "icon_url": null,
    "enable_site": true,
    "enable_api": true,
    "model_config": {
        "pre_prompt": "",
        "prompt_type": "simple",
        "chat_prompt_config": {},
        "completion_prompt_config": {},
        "user_input_form": [],
        "dataset_query_variable": "",
        "more_like_this": {
            "enabled": false
        },
        "opening_statement": "",
        "suggested_questions": [],
        "sensitive_word_avoidance": {
            "enabled": false,
            "type": "",
            "configs": []
        },
        "speech_to_text": {
            "enabled": false
        },
        "text_to_speech": {
            "enabled": false,
            "voice": "",
            "language": ""
        },
        "file_upload": {
            "image": {
                "detail": "high",
                "enabled": false,
                "number_limits": 3,
                "transfer_methods": [
                    "remote_url",
                    "local_file"
                ]
            },
            "enabled": false,
            "allowed_file_types": [],
            "allowed_file_extensions": [
                ".JPG",
                ".JPEG",
                ".PNG",
                ".GIF",
                ".WEBP",
                ".SVG",
                ".MP4",
                ".MOV",
                ".MPEG",
                ".MPGA"
            ],
            "allowed_file_upload_methods": [
                "remote_url",
                "local_file"
            ],
            "number_limits": 3
        },
        "suggested_questions_after_answer": {
            "enabled": false
        },
        "retriever_resource": {
            "enabled": true
        },
        "agent_mode": {
            "max_iteration": 5,
            "enabled": true,
            "strategy": "function_call",
            "tools": [],
            "prompt": null
        },
        "model": {
            "provider": "openai",
            "name": "gpt-4o-mini",
            "mode": "chat",
            "completion_params": {
                "stop": []
            }
        },
        "dataset_configs": {
            "retrieval_model": "multiple",
            "top_k": 4,
            "reranking_enable": true,
            "datasets": {
                "datasets": []
            }
        }
    },
    "workflow": null,
    "site": {
        "access_token": "9ODan2oQLqNkpahH",
        "code": "9ODan2oQLqNkpahH",
        "title": "Agent",
        "icon_type": "emoji",
        "icon": "🤖",
        "icon_background": "#FFEAD5",
        "icon_url": null,
        "description": null,
        "default_language": "en-US",
        "chat_color_theme": null,
        "chat_color_theme_inverted": false,
        "customize_domain": null,
        "copyright": null,
        "privacy_policy": null,
        "custom_disclaimer": "",
        "customize_token_strategy": "not_allow",
        "prompt_public": false,
        "app_base_url": "http://localhost",
        "show_workflow_steps": true,
        "use_icon_as_answer_icon": false,
        "created_by": "2099825c-856e-4ce8-b035-05df64e53470",
        "created_at": 1735865665,
        "updated_by": "2099825c-856e-4ce8-b035-05df64e53470",
        "updated_at": 1735865665
    },
    "api_base_url": "http://localhost/v1",
    "use_icon_as_answer_icon": true,
    "created_by": "2099825c-856e-4ce8-b035-05df64e53470",
    "created_at": 1735865665,
    "updated_by": "2099825c-856e-4ce8-b035-05df64e53470",
    "updated_at": 1736065449,
    "deleted_tools": []
};